# -*- coding: utf-8 -*-

import urllib
import urllib2
import re
import os
import xbmcplugin
import xbmcgui
import xbmcaddon
import zipfile
from BeautifulSoup import BeautifulStoneSoup, BeautifulSoup, BeautifulSOAP

addon = xbmcaddon.Addon('plugin.video.latinatv')
subsystem = addon.getSetting('subsystem')
streamingserver = addon.getSetting('streamingserver')
addon_version = addon.getAddonInfo('version')
addon_name = addon.getAddonInfo('name')
profile = xbmc.translatePath(addon.getAddonInfo('profile').decode('utf-8'))
home = xbmc.translatePath(addon.getAddonInfo('path').decode('utf-8'))
favorites = os.path.join(profile, 'favorites')
REV = os.path.join(profile, 'list_revision')
icon = os.path.join(home, 'icon.png')
FANART = os.path.join(home, 'fanart.jpg')
xbmcmedia = "/media/xbmc/"
subsystempath = "/subsystems/"
UpdateLocalName="update.zip"
UpdatePath=os.path.join(profile,'Update')
try: os.makedirs(UpdatePath)
except: pass

def needUpdate():
	apiurl = "http://iptv.nubeetv.net/api/"
	addon_version = addon.getAddonInfo('version')
	subsystem = addon.getSetting('subsystem')
	fullurlapi = apiurl + 'updates.php?subsystem='+subsystem+'&version='+addon_version
	data = makeRequest(fullurlapi)
	response, url = data.split('|')
	if response.strip() == 'OK':
		return url
	else:
		return -1

def CheckForAutoUpdate():
	UpdateUrl = needUpdate()
	if UpdateUrl != -1:
		UpdateLocalFile = xbmc.translatePath(os.path.join(UpdatePath, UpdateLocalName))
		try:os.remove(UpdateLocalFile)
		except:pass
		try: urllib.urlretrieve(UpdateUrl,UpdateLocalFile)
		except:pass
		if os.path.isfile(UpdateLocalFile):
			xbmc.executebuiltin("XBMC.Notification("+addon_name+",New Update detected,3000,"+icon+")")
			xbmc.executebuiltin("XBMC.Notification("+addon_name+",Updating...,3000,"+icon+")")
			extractFolder = xbmc.translatePath('special://home/addons')
			
			try:
				zin = zipfile.ZipFile(UpdateLocalFile, 'r')
				zin.extractall(extractFolder)
			except Exception, e:
				xbmc.executebuiltin("XBMC.Notification("+addon_name+",Update failed...,3000,"+icon+")")
				return
			
			xbmc.executebuiltin("XBMC.Notification("+addon_name+",Update successful...,3000,"+icon+")")
			xbmcgui.Dialog().ok(addon_name, "New update installed successfully!!!\nplease restart XBMC!")
			xbmc.executebuiltin("XBMC.Container.Refresh")
			return
			
		else:
			return
	else:
		xbmc.executebuiltin("XBMC.Notification("+addon_name+",No update available... ,3000,"+icon+")")
		return
		
def getMacAddress():
	mac_address = xbmc.getInfoLabel("network.macaddress")
	while (mac_address == 'Busy'):
		mac_address = xbmc.getInfoLabel("network.macaddress")
	return mac_address
	
def getPlatform():
	kernelversion = xbmc.getInfoLabel("System.KernelVersion")
	while (kernelversion == 'Busy'):
		kernelversion = xbmc.getInfoLabel("System.KernelVersion")
	return kernelversion;

def makeRequest(url, headers=None):
	stb = getPlatform()
	user_agent = "DroidTV/1.0 ("+stb+" subsystem="+subsystem+", addon="+addon_name+", version="+addon_version+")"
	try:
		if headers is None:
			headers = {'User-agent' : user_agent}

		req = urllib2.Request(url,None,headers)
		response = urllib2.urlopen(req)
		data = response.read()
		response.close()
		return data
	except urllib2.URLError, e:
		if hasattr(e, 'code'):
			xbmc.executebuiltin("XBMC.Notification("+addon_name+",We failed with error code - "+str(e.code)+",10000,"+icon+")")
		elif hasattr(e, 'reason'):
			xbmc.executebuiltin("XBMC.Notification("+addon_name+",We failed to reach a server. - "+str(e.reason)+",10000,"+icon+")")
		return "ERR|"+str(e.reason)

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
            params=sys.argv[2]
            cleanedparams=params.replace('?','')
            if (params[len(params)-1]=='/'):
                params=params[0:len(params)-2]
            pairsofparams=cleanedparams.split('&')
            param={}
            for i in range(len(pairsofparams)):
                splitparams={}
                splitparams=pairsofparams[i].split('=')
                if (len(splitparams))==2:
                    param[splitparams[0]]=splitparams[1]
        return param

def getToken():
	return addon.getSetting('token')


def getChannelServerUrlAccess(StreamingServer):
	token = getToken()
	fullurlapi = 'http://'+StreamingServer+'/play.php?token='+token
	data = makeRequest(fullurlapi)
	response, url = data.split('|')
	if response.strip() == 'OK':
		return 1
	else:
		return -1		
		
def mainMenu():

	mode = '10000'
	settings_name = 'Settings : Please update'
	settings_name = settings_name.encode('utf-8')
	icon = addon.getAddonInfo('icon')
	u=sys.argv[0]+"?"
	u += "&mode="+mode
	liz=xbmcgui.ListItem(settings_name, iconImage="DefaultFolder.png", thumbnailImage=icon)
	liz.setInfo(type="Video", infoLabels={ "Title": settings_name })
	liz.setProperty("IsPlayable" , "false") 
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
	###
	
try:
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
except:
    pass
try:
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
except:
    pass
try:
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE)
except:
    pass
try:
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_GENRE)
except:
    pass

params=get_params()

url=None
name=None
mode=None
iconimage=None
fanart=FANART
channelid=None
groupid=None

try:
    url=urllib.unquote_plus(params["url"]).decode('utf-8')
except:
    pass
try:
    name=urllib.unquote_plus(params["name"])
except:
    pass
try:
    iconimage=urllib.unquote_plus(params["iconimage"])
except:
    pass
try:
    fanart=urllib.unquote_plus(params["fanart"])
except:
    pass
try:
    mode=int(params["mode"])
except:
    pass


if mode==None:
	addon.openSettings(url=sys.argv[0])
	mainMenu()
	xbmcplugin.endOfDirectory(int(sys.argv[1]))
	
if mode==5:
	CheckForAutoUpdate()
	xbmcplugin.endOfDirectory(int(sys.argv[1]))
	
if mode==8:
	mac = getMacAddress()
	builtversion  = xbmc.getInfoLabel("System.BuildVersion")
	kernelversion=getPlatform()
	xbmcgui.Dialog().ok(addon_name, "Add-on version : " +addon_version+ " on "+kernelversion+"\nMAC address : "+mac+"\nBuild version : "+builtversion)
	xbmcplugin.endOfDirectory(int(sys.argv[1]))	
	
if mode==10000:
	addon.openSettings(url=sys.argv[0])
	
xbmcplugin.endOfDirectory (int(sys.argv[1]))
